﻿using Sys.Model;
using Sys.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Sys.Core
{
    /// <summary>
    /// 资源库基类
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public abstract class RepositoryBase<T> where T : class
    {
        #region 属性

        /// <summary>
        /// 数据访问基类
        /// </summary>
        public RepositoryContext<T> RC
        {
            get { return new RepositoryContext<T>(); }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响行数</returns>
        public virtual int Insert(T entity)
        {
            return RC.EntityAdded(entity);
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
        public virtual int Insert(IEnumerable<T> entities)
        {
            return RC.EntitiesAdded(entities);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响行数</returns>
        public virtual int Update(T entity)
        {
            return RC.EntityModified(entity);
        }

        /// <summary>
        /// 批量更新实体
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
        public virtual int Update(IEnumerable<T> entities)
        {
            return RC.EntitiesModified(entities);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响行数</returns>
        public virtual int Delete(T entity)
        {
            return RC.EntityDeleted(entity);
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
        public virtual int Delete(IEnumerable<T> entities)
        {
            return RC.EntitiesDeleted(entities);
        }

        /// <summary>
        /// 根据主键删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>受影响行数</returns>
        public virtual int Delete(object id)
        {
            T entity = RC.Set().Find(id);
            return RC.EntityDeleted(entity);
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <param name="predicate">删除条件</param>
        /// <returns>受影响行数</returns>
        public virtual int Delete(Expression<Func<T, bool>> predicate)
        {
            IEnumerable<T> entities = RC.Set().Where(predicate).AsNoTracking();
            return RC.EntitiesDeleted(entities);
        }

        #endregion
    }
}